package com.gfxy.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        Object obj = request.getSession().getAttribute("user");

        // 白名单路径（不需要登录）
        if (request.getRequestURL().indexOf("regist")>0 || request.getRequestURL().indexOf("login")>0 ||
                request.getRequestURL().indexOf("toNoticeManagePage")>0 || request.getRequestURL().indexOf("toAddNoticePage")>0
                || request.getRequestURL().indexOf("addNotice")>0 || request.getRequestURL().indexOf("toUpdateNoticePage")>0
                || request.getRequestURL().indexOf("updateNotice")>0) {  // 新增白名单
            return true;
        }

        // 已登录用户放行
        if(request.getRequestURL().indexOf("index")>0){
            if (obj != null) {
                return true;
            }
        }
        // 未登录用户重定向到登录页（使用绝对路径）
        if(obj!=null){
            //response.sendRedirect("index");
            return true;
        }else {
            response.sendRedirect("login.jsp");
        }

        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}